<script setup lang="ts">
import * as echarts from 'echarts'
import moment from 'moment/moment'
import { ref } from 'vue'
import { formatDuration } from '@/utils/gps/format'

const props = defineProps({
  data: Object
})
const isShow = ref(true)
let option = {
  dataset: {
    source: [
      ['amount', 'product'],
      [null, '卸货时长'],
      [null, '卸货排队时长'],
      [null, '运输时长'],
      [null, '装货时长'],
      [null, '装货排队时长']
    ]
  },
  grid: {
    left: 0,
    right: 100,
    bottom: 0,
    top: 0,
    containLabel: true
  },
  xAxis: { name: 'amount' },
  yAxis: { type: 'category' },
  series: [
    {
      type: 'bar',
      encode: {
        x: 'amount',
        y: 'product'
      },
      label: {
        position: 'right',
        show: true,
        formatter: function (value) {
          console.log(value)
          if (value.value[0] === 0) {
            return 0
          }
          return formatDuration(value.value[0])
        }
      }
    }
  ]
}

function init(data) {
  if (!data) {
    isShow.value = false
    return
  }
  option.dataset.source = analysis(data) as any
  let chartDom = document.getElementById('freight')
  let myChart = echarts.init(chartDom)
  option && myChart.setOption(option)
}

function analysis(data) {
  //   * startInTime: 进入起点时间
  //   * startOutTime: 离开起点时间
  //   * endInTime: 进入终点时间
  //   * endOutTime: 离开终点时间
  const { startInTime, startOutTime, endInTime, endOutTime } = data
  return [
    ['amount', 'product'],
    [endOutTime && endInTime ? moment(endOutTime).diff(endInTime, 'seconds') : 0, '卸货时长'],
    [endOutTime && endInTime ? moment(endOutTime).diff(endInTime, 'seconds') : 0, '卸货排队时长'],
    [endInTime && startInTime ? moment(endInTime).diff(startInTime, 'seconds') : 0, '运输时长'],
    [
      startOutTime && startInTime ? moment(startOutTime).diff(startInTime, 'seconds') : 0,
      '装货时长'
    ],
    [
      startOutTime && startInTime ? moment(startOutTime).diff(startInTime, 'seconds') : 0,
      '装货排队时长'
    ]
  ]
}

defineExpose({
  init
})
</script>

<template>
  <div v-if="isShow" id="freight" style="width: 1500px; height: 250px"></div>
  <div v-else>暂无数据可以统计</div>
</template>

<style scoped></style>
